﻿using System;
using System.IO;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace TemperatureMicro
{
    public class Program
    {
        public static void Main()
        {

            InterruptPort DeleteFile = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh);
            DeleteFile.OnInterrupt += new NativeEventHandler(ConfigFileDelete);
            
            string macAdress = "Mac-4";
            
            EthernetConfiguration.InitEthernetConfiguration();
            Configuration FileAccess = new Configuration();
            ServerAccess azure = new ServerAccess();
            
            I2CLM75 Sensor = new I2CLM75(macAdress, FileAccess, azure);
            Regulator Regulator = new Regulator(macAdress, Pins.GPIO_PIN_D7, Pins.GPIO_PIN_D6, false, FileAccess, azure);
            
            Debug.Print("Initialiseringerne er færdige.");
            Debug.Print("Sensor Id: " + Sensor.GetId().ToString());
            Debug.Print("Regulator Id: " + Regulator.GetId().ToString());

            while (true)
            {
                Debug.Print("Loop started!");
                Sensor.ReadTemperature();
                Regulator.Regulate();
                Thread.Sleep(5000);
            }
        }

        static void ConfigFileDelete(uint d1, uint d2, DateTime time)
        {
            if (Configuration.RegulatorConfigFilePresent())
                File.Delete(@"\SD\RegulatorConfig.txt");

            if (Configuration.SensorConfigFilePresent())
                File.Delete(@"\SD\SensorConfig.txt");
            
            Debug.Print("Flashed SD Card");
        }
    }
}
